package com.gxs.tga.poc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gxs.tga.poc.domain.TgaCompany;
import com.gxs.tga.poc.domain.TgaSolution;
import com.gxs.tga.poc.domain.exceptions.DuplicateTgaSolution;
import com.gxs.tga.poc.domain.exceptions.TgaSolutionNotFound;
import com.gxs.tga.poc.repository.TgaSolutionRepository;

@Service
public class TgaSolutionServiceImpl implements TgaSolutionService
{

	@Resource
	private TgaSolutionRepository tgaSolutionRepository;

	@Override
	@Transactional
	public TgaSolution create(TgaSolution solution) throws DuplicateTgaSolution
	{
		TgaSolution existingSolution = this.findById(solution.getSolutionId());
		if(existingSolution != null)
		{
			throw new DuplicateTgaSolution();
		}
		TgaSolution createdTgaSolution = solution;
		
		return tgaSolutionRepository.save(createdTgaSolution);
	}

	@Override
	@Transactional
	public TgaSolution findById(String solutionId)
	{
		return tgaSolutionRepository.findOne(solutionId);
	}

	@Override
	@Transactional(rollbackFor = TgaSolutionNotFound.class)
	public TgaSolution delete(String solutionId) throws TgaSolutionNotFound
	{
		TgaSolution deletedTgaSolution = tgaSolutionRepository.findOne(solutionId);

		if (deletedTgaSolution == null)
			throw new TgaSolutionNotFound();

		tgaSolutionRepository.delete(deletedTgaSolution);
		return deletedTgaSolution;
	}

	@Override
	@Transactional
	public List<TgaSolution> findAll()
	{
		return tgaSolutionRepository.findAll(new Sort(Sort.Direction.ASC, "solutionId"));
		
	}

	@Override
	@Transactional(rollbackFor=TgaSolutionNotFound.class)
	public TgaSolution update(TgaSolution solution) throws TgaSolutionNotFound {
		TgaSolution updatedTgaSolution = tgaSolutionRepository.findOne(solution.getSolutionId());
		
		if (updatedTgaSolution == null)
			throw new TgaSolutionNotFound();
		
		updatedTgaSolution.setDescription(solution.getDescription());
		updatedTgaSolution.setTgaCompany(solution.getTgaCompany());
		
		return updatedTgaSolution;
	}
	
	@Override
	@Transactional
	public List<TgaSolution> findByTgaCompany(TgaCompany tgaCompany)
	{
		return this.tgaSolutionRepository.findByTgaCompany(tgaCompany);
	}


}
